 <template>
  <div class="warehouse-add-container">
    <!-- 基础信息 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">基础信息</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="add-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库编号">
              <el-input placeholder="自动获取系统编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName" required>
              <el-input v-model="formData.warehouseName" placeholder="请输入仓库名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>


        

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库容量/m³" prop="warehousecapacity">
              <el-input v-model="formData.warehousecapacity" placeholder="请输入仓库容量" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库管部门" prop="warehouseDeptId">
              <el-input 
                v-model="selectedDepartmentName" 
                placeholder="请选择库管部门" 
                readonly
                style="cursor: pointer;"
                @click="departmentDialogVisible = true"
              >
                <template #suffix>
                  <el-icon 
                    class="more-icon" 
                    @click.stop="departmentDialogVisible = true"
                  >
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库主管" prop="supervisorId">
              <el-input 
                v-model="selectedSupervisorName" 
                placeholder="请选择仓库主管" 
                readonly
                style="cursor: pointer;"
                @click="supervisorDialogVisible = true"
              >
                <template #suffix>
                  <el-icon 
                    class="more-icon" 
                    @click.stop="supervisorDialogVisible = true"
                  >
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="warehousePhone">
              <el-input v-model="formData.warehousePhone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="仓库地址" prop="warehouseAddress">
              <el-input v-model="formData.warehouseAddress" placeholder="请输入仓库地址" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库状态" prop="warehouseState">
              <el-radio-group v-model="formData.warehouseState">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.warehouseState === 1" :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库锁定" prop="warehouseLockdown">
              <el-switch v-model="formData.warehouseLockdown" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="warehouseContent">
              <el-input v-model="formData.warehouseContent" type="textarea" :rows="4" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 库位信息 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">库位信息</span>
        </div>
      </template>

      <div class="toolbar">
        <el-button type="success" @click="handleAddLocation">添加</el-button>
        <el-button type="danger" @click="handleRemoveLocations">删除</el-button>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          accept=".xlsx,.xls"
          :on-change="handleImportChange"
          style="display: inline-block; margin-left: 8px"
        >
          <el-button>导入</el-button>
        </el-upload>
        <el-button @click="handleExportLocation">导出</el-button>
        <el-button @click="handleDownloadTemplate">下载模板</el-button>
      </div>

      <el-table :data="locations" style="width: 100%" border stripe @selection-change="handleLocationSelectionChange"
        v-loading="tableLoading">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="storagelocationCode" label="库位编号" width="120" />
        <el-table-column prop="storagelocationName" label="库位名称" width="120" />
        <el-table-column prop="storagelocationCapacity" label="库位容量/m³" width="140" align="center" />
        <el-table-column prop="supervisorName" label="库位主管" width="150" />
        <el-table-column prop="storagelocationScore" label="排序" width="100" align="center" />
        <el-table-column prop="storagelocationState" label="库位状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.storagelocationState === 1 ? 'success' : 'danger'">
              {{ row.storagelocationState === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationContent" label="备注" min-width="150" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEditLocation(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleRemoveLocation(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination 
          v-model:current-page="locationPage" 
          v-model:page-size="locationPageSize"
          :page-sizes="[10, 20, 50, 100]" 
          :total="locationTotal"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleLocationSizeChange" 
          @current-change="handleLocationPageChange" 
        />
      </div>
    </el-card>

    <!-- 底部操作按钮 -->
    <div class="footer-actions">
      <el-button @click="handleClose">关闭</el-button>
      <el-button @click="handleSaveDraft">保存为草稿</el-button>
      <el-button @click="handleSaveAsNew">保存为新增</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>

    <!-- 库位新增/编辑抽屉 -->
    <el-drawer v-model="locationDrawerVisible" :title="locationDrawerTitle" size="500px"
      :before-close="handleLocationDrawerClose">
      <el-form :model="locationForm" :rules="locationRules" ref="locationFormRef" label-width="120px"
        class="drawer-form">
        <el-form-item label="库位编号">
          <el-input v-model="locationForm.storagelocationCode" placeholder="自动获取系统编号" disabled />
        </el-form-item>

        <el-form-item label="库位名称" prop="storagelocationName" required>
          <el-input v-model="locationForm.storagelocationName" placeholder="请输入库位名称" clearable />
        </el-form-item>

        <el-form-item label="库位容量/m³" prop="storagelocationCapacity" required>
          <el-input v-model="locationForm.storagelocationCapacity" placeholder="请输入库位容量" clearable />
        </el-form-item>

        <el-form-item label="库位主管" prop="supervisorId" required>
          <el-select v-model="locationForm.supervisorId" placeholder="请选择库位主管" style="width: 100%">
            <el-option v-for="item in supervisorList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="库位状态" prop="storagelocationState" required>
          <el-radio-group v-model="locationForm.storagelocationState">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="storagelocationScore" required>
          <el-input-number v-model="locationForm.storagelocationScore" :min="0" placeholder="请输入排序"
            style="width: 100%" />
        </el-form-item>

        <!-- <el-form-item label="操作人" prop="operatorName" required>
          <el-select v-model="locationForm.operatorName" placeholder="请选择操作人" style="width: 100%">
            <el-option v-for="item in operatorList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="备注" prop="storagelocationContent" required>
          <el-input v-model="locationForm.storagelocationContent" type="textarea" :rows="4" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="handleLocationDrawerClose">取消</el-button>
          <el-button type="primary" @click="handleLocationSave" :loading="saveLoading">保存</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 仓库主管选择对话框 -->
    <el-dialog
      v-model="supervisorDialogVisible"
      title="选择人员"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="supervisor-dialog">
        <el-input
          v-model="supervisorSearchKeyword"
          placeholder="请搜索"
          clearable
          class="search-input"
        >
          <template #suffix>
            <el-icon class="search-icon"><Search /></el-icon>
          </template>
        </el-input>

        <div class="supervisor-list">
          <div class="list-title">仓储部</div>
          <div 
            v-for="item in filteredSupervisorList" 
            :key="item.value"
            class="supervisor-item"
            :class="{ 'is-selected': selectedSupervisorId === item.value }"
            @click="handleSelectSupervisor(item)"
          >
            <span>{{ item.label }}</span>
            <el-icon v-if="selectedSupervisorId === item.value" class="check-icon" color="#67C23A">
              <Check />
            </el-icon>
          </div>
          <div v-if="filteredSupervisorList.length === 0" class="empty-text">
            暂无数据
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="supervisorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmSupervisor">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 库管部门选择对话框 -->
    <el-dialog
      v-model="departmentDialogVisible"
      title="选择部门"
      width="520px"
      :close-on-click-modal="false"
      class="department-cascader-dialog"
    >
      <div class="department-dialog">
        <el-input
          v-model="departmentSearchKeyword"
          placeholder="请搜索部门"
          clearable
          class="search-input"
          size="large"
        >
          <template #prefix>
            <el-icon class="search-icon"><Search /></el-icon>
          </template>
        </el-input>

        <div class="department-tree-list">
          <div 
            v-for="item in filteredDepartmentList" 
            :key="item.value"
            class="tree-item"
          >
            <div 
              class="tree-item-content"
              :class="{ 
                'is-selected': selectedDepartmentId === item.value,
                'has-children': item.children && item.children.length > 0
              }"
              :style="{ paddingLeft: '20px' }"
              @click="handleSelectDepartment(item)"
            >
              <span class="tree-item-expand" @click.stop="toggleExpand(item)">
                <span v-if="item.children && item.children.length > 0" class="expand-arrow">
                  {{ item.expanded ? '▼' : '►' }}
                </span>
                <span v-else class="leaf-dot">•</span>
              </span>
              <span class="tree-item-label">{{ item.label }}</span>
              <span v-if="selectedDepartmentId === item.value" class="check-icon">✓</span>
            </div>
            
            <!-- 递归渲染子节点 -->
            <template v-if="item.expanded && item.children && item.children.length > 0">
              <tree-node 
                v-for="child in item.children" 
                :key="child.value"
                :node="child"
                :level="1"
                :selected-id="selectedDepartmentId"
                :search-keyword="departmentSearchKeyword"
                @select="handleSelectDepartment"
                @toggle="toggleExpand"
              />
            </template>
          </div>
          <div v-if="filteredDepartmentList.length === 0" class="empty-text">
            暂无数据
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="departmentDialogVisible = false" size="default">取消</el-button>
          <el-button type="primary" @click="handleConfirmDepartment" size="default">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, h, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus'
import { MoreFilled, Search, Check, ArrowRight, ArrowDown } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
// 导入库位API和仓库API
import {
  addStoragelocation,
  updateStoragelocation,
  deleteStoragelocation,
  queryStoragelocation,
  getOperatorList,
  getSupervisorList,
  getWarehouseSupervisorList,
  getDeptCascaderList,
  addWarehouse,
  getWarehouseOperatorName
} from '@/api/storagelocation'

const router = useRouter()

// 基础信息表单引用
const formRef = ref<FormInstance>()

// 表单数据（对应后端字段）
const formData = reactive({
  warehouseID: 0, // 仓库ID
  warehouseCode: 0, // 仓库编号，从后端获取
  warehouseName: '', // 仓库名称
  warehousecapacity: '', // 仓库容量
  supervisorId: 0, // 仓库主管ID
  warehouseDeptId: 0, // 库管部门ID
  warehousePhone: '', // 联系电话
  warehouseAddress: '', // 仓库地址
  warehouseState: 1, // 仓库状态：1-启用，0-停用
  warehouseLockdown: false, // 仓库锁定
  warehouseContent: '', // 备注
  dataStatus: 0, // 数据状态：1-草稿，2-新增，3-保存
  operatorName: '', // 操作人名称，从后端获取
  sort: '' // 排序（前端使用）
})

// 基础信息表单验证规则
const formRules = reactive<FormRules>({
  warehouseName: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' }
  ],
  warehousecapacity: [
    { required: true, message: '请输入仓库容量', trigger: 'blur' }
  ],
  warehouseDeptId: [
    { required: true, message: '请选择库管部门', trigger: 'change' }
  ],
  supervisorId: [
    { required: true, message: '请选择仓库主管', trigger: 'change' }
  ],
  warehousePhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  warehouseAddress: [
    { required: true, message: '请输入仓库地址', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  warehouseState: [
    { required: true, message: '请选择仓库状态', trigger: 'change' }
  ]
})


// 库位数据
const locations = ref<any[]>([])
const selectedLocations = ref<any[]>([])
const locationPage = ref(1)
const locationPageSize = ref(10)
const locationTotal = ref(0)
const tableLoading = ref(false)
const saveLoading = ref(false)

// 库位抽屉
const locationDrawerVisible = ref(false)
const locationDrawerTitle = ref('新增')
const locationDrawerMode = ref<'add' | 'edit'>('add')
const locationFormRef = ref<FormInstance>()

// 库位表单
const locationForm = reactive({
  storagelocationId: undefined as number | undefined,
  storagelocationCode: '',
  storagelocationName: '',
  storagelocationCapacity: '',
  storagelocationState: 1,
  storagelocationContent: '',
  storagelocationScore: 0,
  supervisorId: undefined as number | undefined,
  dataStatus: 0,
  operatorName: ''
})

// 表单验证规则
const locationRules = reactive<FormRules>({
  storagelocationName: [
    { required: true, message: '请输入库位名称', trigger: 'blur' }
  ],
  storagelocationCapacity: [
    { required: true, message: '请输入库位容量', trigger: 'blur' }
  ],
  supervisorId: [
    { required: true, message: '请选择库位主管', trigger: 'change' }
  ],
  storagelocationState: [
    { required: true, message: '请选择库位状态', trigger: 'change' }
  ],
  storagelocationScore: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  operatorName: [
    { required: true, message: '请选择操作人', trigger: 'change' }
  ],
  storagelocationContent: [
    { required: true, message: '请输入备注', trigger: 'blur' }
  ]
})

// 操作人列表
const operatorList = ref<{ label: string; value: string }[]>([])

// 主管列表
const supervisorList = ref<{ label: string; value: number }[]>([])

// 上传组件引用
const uploadRef = ref()

// 仓库主管选择对话框
const supervisorDialogVisible = ref(false)
const supervisorSearchKeyword = ref('')
const selectedSupervisorId = ref<number | undefined>(undefined)
const selectedSupervisorName = ref('')

// 过滤后的主管列表
const filteredSupervisorList = computed(() => {
  if (!supervisorSearchKeyword.value) {
    return supervisorList.value
  }
  return supervisorList.value.filter(item => 
    item.label.toLowerCase().includes(supervisorSearchKeyword.value.toLowerCase())
  )
})

// 库管部门选择对话框
const departmentDialogVisible = ref(false)
const selectedDepartmentId = ref<number | undefined>(undefined)
const selectedDepartmentName = ref('')
const departmentCascaderOptions = ref<any[]>([])
const departmentSearchKeyword = ref('')

// 树形节点组件
const TreeNode = {
  name: 'TreeNode',
  props: {
    node: Object,
    level: Number,
    selectedId: Number,
    searchKeyword: String
  },
  emits: ['select', 'toggle'],
  setup(props: any, { emit }: any) {
    const handleSelect = () => {
      emit('select', props.node)
    }
    
    const handleToggle = () => {
      emit('toggle', props.node)
    }
    
    const paddingLeft = computed(() => `${20 + props.level * 20}px`)
    
    return () => {
      const { node, selectedId, searchKeyword } = props
      
      // 如果有搜索关键词，检查是否匹配
      if (searchKeyword && !node.label.toLowerCase().includes(searchKeyword.toLowerCase())) {
        // 检查子节点是否有匹配
        const hasMatchingChild = (n: any): boolean => {
          if (n.label.toLowerCase().includes(searchKeyword.toLowerCase())) return true
          if (n.children && n.children.length > 0) {
            return n.children.some((child: any) => hasMatchingChild(child))
          }
          return false
        }
        
        if (!hasMatchingChild(node)) {
          return null
        }
      }
      
      return h('div', { class: 'tree-item' }, [
        h('div', {
          class: [
            'tree-item-content', 
            { 
              'is-selected': selectedId === node.value,
              'has-children': node.children && node.children.length > 0
            }
          ],
          style: { paddingLeft: paddingLeft.value },
          onClick: handleSelect
        }, [
          h('span', {
            class: 'tree-item-expand',
            onClick: (e: Event) => {
              e.stopPropagation()
              handleToggle()
            }
          }, [
            node.children && node.children.length > 0 
              ? h('span', { class: 'expand-arrow' }, node.expanded ? '▼' : '►')
              : h('span', { class: 'leaf-dot' }, '•')
          ]),
          h('span', { class: 'tree-item-label' }, node.label),
          selectedId === node.value ? h('span', { class: 'check-icon' }, '✓') : null
        ]),
        node.expanded && node.children && node.children.length > 0 ? node.children.map((child: any) => 
          h(TreeNode, {
            node: child,
            level: props.level + 1,
            selectedId: selectedId,
            searchKeyword: searchKeyword,
            onSelect: (n: any) => emit('select', n),
            onToggle: (n: any) => emit('toggle', n)
          })
        ) : null
      ])
    }
  }
}

// 过滤后的部门列表
const filteredDepartmentList = computed(() => {
  if (!departmentSearchKeyword.value) {
    return departmentCascaderOptions.value
  }
  
  // 递归过滤
  const filterTree = (nodes: any[]): any[] => {
    return nodes.filter(node => {
      const matches = node.label.toLowerCase().includes(departmentSearchKeyword.value.toLowerCase())
      const hasMatchingChildren = node.children && node.children.length > 0 && filterTree(node.children).length > 0
      return matches || hasMatchingChildren
    }).map(node => ({
      ...node,
      expanded: true // 搜索时自动展开
    }))
  }
  
  return filterTree(departmentCascaderOptions.value)
})

// ==================== API接口区域 ====================

/**
 * 获取操作人名称
 * API: GET http://localhost:5079/api/Warehouse/GetOperatorName
 */
const fetchOperatorName = async () => {
  try {
    const response: any = await getWarehouseOperatorName()
    if (response && response.code === 200 && response.data) {
      formData.operatorName = response.data
    } else if (response && response.data) {
      formData.operatorName = response.data
    }
  } catch (error) {
    console.warn('获取操作人名称失败')
    formData.operatorName = '系统管理员'
  }
}

/**
 * 获取操作人列表
 * API: GET /api/Users/GetOperatorList
 */
const fetchOperatorList = async () => {
  try {
    const response: any = await getOperatorList()
    if (response.code === 200 && response.data) {
      operatorList.value = response.data.map((item: any) => ({
        label: item.name,
        value: item.name
      }))
    }
  } catch (error) {
    console.warn('获取操作人列表失败，使用模拟数据')
    // 开发阶段使用模拟数据
    operatorList.value = [
      { label: '张三', value: '张三' },
      { label: '李四', value: '李四' },
      { label: '王五', value: '王五' }
    ]
  }
}

/**
 * 获取主管列表（仓库主管）
 * API: GET /api/WarehouseSupervisor/WarehousesupervisorsQuery
 */
const fetchSupervisorList = async () => {
  try {
    const response: any = await getWarehouseSupervisorList()
    if (response.code === 200 && response.data) {
      // console.log(response.data)
      // 根据后端返回的数据结构进行映射
      supervisorList.value = response.data.map((item: any) => ({
        label: item.supervisorName || item.name,
        value: item.supervisorId || item.id
      }))
    }
  } catch (error) {
    console.warn('获取仓库主管列表失败，使用模拟数据')
    // 开发阶段使用模拟数据
    supervisorList.value = [
      { label: '赵欣美', value: 1 },
      { label: '潘雨怡', value: 2 },
      { label: '宋欧欣', value: 3 }
    ]
  }
}

/**
 * 获取部门级联数据
 * API: GET /api/WarehouseDept/GetDeptCascader?parentId=0
 */
const fetchDeptCascader = async () => {
  try {
    const response: any = await getDeptCascaderList(0)
    if (response.code === 200 && response.data) {
      // 添加 expanded 属性，默认全部展开
      const addExpandedProp = (nodes: any[]): any[] => {
        return nodes.map(node => ({
          ...node,
          expanded: true, // 改为 true，默认展开
          children: node.children ? addExpandedProp(node.children) : []
        }))
      }
      departmentCascaderOptions.value = addExpandedProp(response.data)
    }
  } catch (error) {
    console.warn('获取部门级联数据失败，使用模拟数据')
    // 开发阶段使用模拟数据
    departmentCascaderOptions.value = [
      {
        value: 1,
        label: '八维集团',
        expanded: true, // 改为 true，默认展开
        children: [
          {
            value: 2,
            label: '研发部门',
            expanded: true, // 改为 true，默认展开
            children: [
              {
                value: 3,
                label: '软件开发部门',
                expanded: true, // 改为 true，默认展开
                children: [
                  { value: 4, label: 'Java开发部', expanded: true, children: [] }
                ]
              }
            ]
          },
          { value: 5, label: '移动端开发部', expanded: true, children: [] }
        ]
      }
    ]
  }
}

/**
 * 查询库位信息
 * API: GET /api/Storagelocation/QueryStoragelocation
 */
const fetchLocationList = async () => {
  try {
    tableLoading.value = true
    const response: any = await queryStoragelocation({
      PageIndex: locationPage.value,
      PageSize: locationPageSize.value
    })

    if (response.code === 200 && response.data) {
      console.log(response.data.data)
      locations.value = response.data.data || []
      locationTotal.value = response.data.totalCount || 0
      
    }
  } catch (error) {
    console.error('查询库位信息失败:', error)
    ElMessage.error('查询库位信息失败')
  } finally {
    tableLoading.value = false
  }
}

/**
 * 保存仓库（草稿）
 * API: POST /api/warehouse/saveDraft
 */
const saveWarehouseDraft = async () => {
  try {
    const params = {
      ...formData,
      locations: locations.value
    }

    console.log('保存草稿参数:', params)
    // TODO: 调用后端API
    // const response = await saveWarehouseDraft(params)
    // return response.data

    return { success: true, message: '保存草稿成功' }
  } catch (error) {
    console.warn('API未实现，使用模拟数据')
    return { success: true, message: '保存草稿成功' }
  }
}

/**
 * 保存仓库
 * API: POST /api/warehouse/save
 */
const saveWarehouseData = async () => {
  try {
    const params = {
      ...formData,
      locations: locations.value
    }

    console.log('保存参数:', params)
    // TODO: 调用后端API
    // const response = await saveWarehouse(params)
    // return response.data

    return { success: true, message: '保存成功' }
  } catch (error) {
    console.warn('API未实现，使用模拟数据')
    return { success: true, message: '保存成功' }
  }
}

// ==================== 页面逻辑 ====================

// 选择主管
const handleSelectSupervisor = (item: { label: string; value: number }) => {
  selectedSupervisorId.value = item.value
}

// 确认选择主管
const handleConfirmSupervisor = () => {
  if (selectedSupervisorId.value !== undefined) {
    formData.supervisorId = selectedSupervisorId.value
    const selectedItem = supervisorList.value.find(item => item.value === selectedSupervisorId.value)
    if (selectedItem) {
      selectedSupervisorName.value = selectedItem.label
    }
  }
  supervisorDialogVisible.value = false
}

// 选择部门
const handleSelectDepartment = (node: any) => {
  selectedDepartmentId.value = node.value
}

// 切换展开/收起
const toggleExpand = (node: any) => {
  node.expanded = !node.expanded
}

// 确认选择部门
const handleConfirmDepartment = () => {
  if (selectedDepartmentId.value !== undefined) {
    formData.warehouseDeptId = selectedDepartmentId.value
    
    // 获取完整路径
    const getNodePath = (nodes: any[], targetValue: number, path: string[] = []): string[] | null => {
      for (const node of nodes) {
        const currentPath = [...path, node.label]
        if (node.value === targetValue) {
          return currentPath
        }
        if (node.children && node.children.length > 0) {
          const result = getNodePath(node.children, targetValue, currentPath)
          if (result) return result
        }
      }
      return null
    }
    
    const path = getNodePath(departmentCascaderOptions.value, selectedDepartmentId.value)
    selectedDepartmentName.value = path ? path.join(' / ') : ''
  }
  departmentDialogVisible.value = false
}

// 监听仓库状态变化
watch(() => formData.warehouseState, (newStatus) => {
  // 当状态切换为停用时，自动将仓库锁定设置为 false
  if (newStatus === 0) {
    formData.warehouseLockdown = false
  }
})

// 初始化
onMounted(() => {
  // 仓库编号由后端自动生成，不需要前端获取
  fetchOperatorName()
  fetchOperatorList()
  fetchSupervisorList()
  fetchDeptCascader()
  fetchLocationList()
})

// 添加库位
const handleAddLocation = () => {
  locationDrawerMode.value = 'add'
  locationDrawerTitle.value = '新增'

  // 重置表单数据
  locationForm.storagelocationId = undefined
  locationForm.storagelocationCode = '系统自动生成'
  locationForm.storagelocationName = ''
  locationForm.storagelocationCapacity = ''
  locationForm.storagelocationState = 1
  locationForm.storagelocationContent = ''
  locationForm.storagelocationScore = 0
  locationForm.supervisorId = undefined
  locationForm.dataStatus = 0
  locationForm.operatorName = ''

  // 打开抽屉
  locationDrawerVisible.value = true

  // 在 DOM 更新后清除表单验证
  nextTick(() => {
    locationFormRef.value?.clearValidate()
  })
}

// 删除选中库位
const handleRemoveLocations = async () => {
  if (selectedLocations.value.length === 0) {
    ElMessage.warning('请选择要删除的库位')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedLocations.value.length} 个库位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 提示选择操作人
      const operatorName = await ElMessageBox.prompt('请输入操作人名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '操作人名称不能为空'
      })

      if (operatorName.value) {
        // 批量删除
        for (const item of selectedLocations.value) {
          await deleteStoragelocation(item.storagelocationId, operatorName.value)
        }
        ElMessage.success('删除成功')
        fetchLocationList()
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  })
}

// 删除单个库位
const handleRemoveLocation = async (row: any) => {
  ElMessageBox.confirm('确定要删除该库位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 提示选择操作人
      const operatorName = await ElMessageBox.prompt('请输入操作人名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '操作人名称不能为空'
      })

      if (operatorName.value) {
        await deleteStoragelocation(row.storagelocationId, operatorName.value)
        ElMessage.success('删除成功')
        fetchLocationList()
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  })
}

// 编辑库位
const handleEditLocation = (row: any) => {
  locationDrawerMode.value = 'edit'
  locationDrawerTitle.value = '编辑'

  // 填充表单
  Object.assign(locationForm, {
    storagelocationId: row.storagelocationId,
    storagelocationCode: row.storagelocationCode,
    storagelocationName: row.storagelocationName,
    storagelocationCapacity: row.storagelocationCapacity,
    storagelocationState: row.storagelocationState,
    storagelocationContent: row.storagelocationContent,
    storagelocationScore: row.storagelocationScore,
    supervisorId: row.supervisorId,
    dataStatus: row.dataStatus || 0,
    operatorName: ''
  })

  locationDrawerVisible.value = true
}

// 关闭库位抽屉
const handleLocationDrawerClose = () => {
  locationDrawerVisible.value = false
  locationFormRef.value?.resetFields()
}

// 保存库位
const handleLocationSave = async () => {
  // 表单验证
  if (!locationFormRef.value) return

  await locationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        saveLoading.value = true

        const params = {
          storagelocationId: locationForm.storagelocationId,
          storagelocationCode: locationForm.storagelocationCode,
          storagelocationName: locationForm.storagelocationName,
          storagelocationCapacity: locationForm.storagelocationCapacity,
          storagelocationState: locationForm.storagelocationState,
          storagelocationContent: locationForm.storagelocationContent,
          storagelocationScore: locationForm.storagelocationScore,
          supervisorId: locationForm.supervisorId!,
          dataStatus: locationForm.dataStatus,
          operatorName: locationForm.operatorName
        }

        if (locationDrawerMode.value === 'add') {
          // 新增
          await addStoragelocation(params)
          ElMessage.success('添加成功')
        } else {
          // 编辑
          if (params.storagelocationId !== undefined) {
            await updateStoragelocation({
              ...params,
              storagelocationId: params.storagelocationId
            })
            ElMessage.success('编辑成功')
          } else {
            ElMessage.error('库位ID不存在')
            return
          }
        }

        locationDrawerVisible.value = false
        fetchLocationList()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saveLoading.value = false
      }
    } else {
      ElMessage.warning('请填写完整信息')
    }
  })
}

// 下载模板
const handleDownloadTemplate = () => {
  // 创建模板数据
  const templateData = [
    {
      '库位名称': '示例库位A',
      '库位容量': '100',
      '库位状态': '1',
      '备注': '这是备注信息',
      '排序': '1',
      '主管ID': '1',
      '操作人': 'System'
    }
  ]

  // 创建工作表
  const ws = XLSX.utils.json_to_sheet(templateData)
  
  // 设置列宽
  ws['!cols'] = [
    { wch: 20 }, // 库位名称
    { wch: 15 }, // 库位容量
    { wch: 15 }, // 库位状态
    { wch: 30 }, // 备注
    { wch: 10 }, // 排序
    { wch: 15 }, // 主管ID
    { wch: 15 }  // 操作人
  ]

  // 创建工作簿
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '库位信息模板')

  // 导出文件
  XLSX.writeFile(wb, '库位信息导入模板.xlsx')
  
  ElMessage.success('模板下载成功')
}

// 导入库位 - 文件变化处理
const handleImportChange: UploadProps['onChange'] = async (file) => {
  const rawFile = file.raw
  if (!rawFile) return

  try {
    // 读取文件
    const data = await rawFile.arrayBuffer()
    const workbook = XLSX.read(data, { type: 'array' })
    
    // 获取第一个工作表
    const firstSheetName = workbook.SheetNames[0]
    if (!firstSheetName) {
      ElMessage.error('Excel文件格式错误')
      return
    }
    
    const worksheet = workbook.Sheets[firstSheetName]
    if (!worksheet) {
      ElMessage.error('Excel文件中没有工作表')
      return
    }
    
    // 转换为JSON
    const jsonData = XLSX.utils.sheet_to_json(worksheet) as any[]
    
    if (jsonData.length === 0) {
      ElMessage.warning('Excel文件中没有数据')
      return
    }

    // 验证并转换数据
    const importData = []
    for (let i = 0; i < jsonData.length; i++) {
      const row = jsonData[i]
      
      // 验证必填字段
      if (!row['库位名称']) {
        ElMessage.error(`第 ${i + 2} 行：库位名称不能为空`)
        return
      }
      if (!row['库位容量']) {
        ElMessage.error(`第 ${i + 2} 行：库位容量不能为空`)
        return
      }
      if (!row['库位状态']) {
        ElMessage.error(`第 ${i + 2} 行：库位状态不能为空`)
        return
      }
      if (!row['备注']) {
        ElMessage.error(`第 ${i + 2} 行：备注不能为空`)
        return
      }
      if (row['排序'] === undefined) {
        ElMessage.error(`第 ${i + 2} 行：排序不能为空`)
        return
      }
      if (!row['主管ID']) {
        ElMessage.error(`第 ${i + 2} 行：主管ID不能为空`)
        return
      }
      if (!row['操作人']) {
        ElMessage.error(`第 ${i + 2} 行：操作人不能为空`)
        return
      }

      // 验证库位状态（必须是1或2）
      const state = Number(row['库位状态'])
      if (state !== 1 && state !== 2) {
        ElMessage.error(`第 ${i + 2} 行：库位状态必须是1(启用)或2(禁用)`)
        return
      }

      importData.push({
        storagelocationName: String(row['库位名称']),
        storagelocationCapacity: String(row['库位容量']),
        storagelocationState: state,
        storagelocationContent: String(row['备注']),
        storagelocationScore: Number(row['排序']) || 0,
        supervisorId: Number(row['主管ID']),
        dataStatus: 0,
        operatorName: String(row['操作人'])
      })
    }

    // 批量导入
    let successCount = 0
    let failCount = 0
    
    for (const item of importData) {
      try {
        await addStoragelocation(item)
        successCount++
      } catch (error) {
        console.error('导入失败:', error)
        failCount++
      }
    }

    // 刷新列表
    await fetchLocationList()

    // 显示结果
    if (failCount === 0) {
      ElMessage.success(`成功导入 ${successCount} 条数据`)
    } else {
      ElMessage.warning(`成功导入 ${successCount} 条，失败 ${failCount} 条`)
    }

    // 清空上传组件
    uploadRef.value?.clearFiles()

  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败，请检查文件格式')
  }
}

// 导出库位
const handleExportLocation = () => {
  if (locations.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  try {
    // 准备导出数据
    const exportData = locations.value.map((item, index) => ({
      '序号': index + 1,
      '库位编号': item.storagelocationCode || '',
      '库位名称': item.storagelocationName || '',
      '库位容量': item.storagelocationCapacity || '',
      '库位主管': item.supervisorName || '',
      '排序': item.storagelocationScore || 0,
      '库位状态': item.storagelocationState === 1 ? '启用' : '禁用',
      '备注': item.storagelocationContent || ''
    }))

    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData)
    
    // 设置列宽
    ws['!cols'] = [
      { wch: 8 },  // 序号
      { wch: 15 }, // 库位编号
      { wch: 20 }, // 库位名称
      { wch: 15 }, // 库位容量
      { wch: 15 }, // 库位主管
      { wch: 10 }, // 排序
      { wch: 15 }, // 库位状态
      { wch: 30 }  // 备注
    ]

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '库位信息')

    // 生成文件名（带时间戳）
    const fileName = `库位信息_${new Date().getTime()}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 库位选择变化
const handleLocationSelectionChange = (selection: any[]) => {
  selectedLocations.value = selection
}

// 库位分页
const handleLocationSizeChange = (val: number) => {
  locationPageSize.value = val
  fetchLocationList()
}

const handleLocationPageChange = (val: number) => {
  locationPage.value = val
  fetchLocationList()
}

// 关闭
const handleClose = () => {
  router.back()
}

// 保存为草稿
const handleSaveDraft = async () => {
  // dataStatus赋值为1
  formData.dataStatus = 1
  // 仓库编号由后端自动生成，确保传0
  formData.warehouseCode = 0
  
  try {
    saveLoading.value = true
    const response: any = await addWarehouse(formData)
    
    if (response && (response.code === 400 || response.success)) {
      ElMessage.success('保存草稿成功')
      router.back()
    } else {
      ElMessage.error(response.message || '保存草稿失败')
    }
  } catch (error: any) {
    console.error('保存草稿失败：', error)
    ElMessage.error(error.message || '保存草稿失败')
  } finally {
    saveLoading.value = false
  }
}

// 保存为新增
const handleSaveAsNew = async () => {
  // 表单验证
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    ElMessage.warning('请填写完整的表单信息')
    return
  }

  // dataStatus赋值为2
  formData.dataStatus = 2
  // 仓库编号由后端自动生成，确保传0
  formData.warehouseCode = 0

  try {
    saveLoading.value = true
    const response: any = await addWarehouse(formData)
    
    if (response && (response.code === 400 || response.success)) {
      ElMessage.success('保存成功')
      // 保存后继续新增，重置表单
      Object.assign(formData, {
        warehouseID: 0,
        warehouseCode: 0,
        warehouseName: '',
        warehousecapacity: '',
        supervisorId: 0,
        warehouseDeptId: 0,
        warehousePhone: '',
        warehouseAddress: '',
        warehouseState: 1,
        warehouseLockdown: false,
        warehouseContent: '',
        dataStatus: 0,
        operatorName: '',
        sort: ''
      })
      selectedSupervisorName.value = ''
      selectedDepartmentName.value = ''
      locations.value = []
      // 重新获取操作人名称（仓库编号由后端自动生成）
      fetchOperatorName()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存失败：', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 保存
const handleSave = async () => {
  // 表单验证
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    ElMessage.warning('请填写完整的表单信息')
    return
  }

  // dataStatus赋值为3
  formData.dataStatus = 3
  // 仓库编号由后端自动生成，确保传0
  formData.warehouseCode = 0

  try {
    saveLoading.value = true
    const response: any = await addWarehouse(formData)
    
    if (response && (response.code === 400 || response.success)) {
      ElMessage.success('保存成功')
      router.back()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存失败：', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saveLoading.value = false
  }
}
</script>

<style scoped>
.warehouse-add-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-card {
  margin-bottom: 0;
}

.section-card :deep(.el-card__body) {
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.add-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

.add-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.input-with-action {
  display: flex;
  align-items: center;
  width: 100%;
}

.toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  padding: 16px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to bottom, transparent, #f8f9fa);
  border-radius: 8px;
}

.pagination-container :deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-container :deep(.el-pagination__total) {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.pagination-container :deep(.el-pagination__sizes) {
  margin: 0;
}

.pagination-container :deep(.el-select) {
  width: 120px;
}

.pagination-container :deep(.btn-prev),
.pagination-container :deep(.btn-next) {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  font-weight: 500;
  padding: 0 12px;
  height: 32px;
  min-width: 32px;
  transition: all 0.3s ease;
}

.pagination-container :deep(.btn-prev):hover:not(:disabled),
.pagination-container :deep(.btn-next):hover:not(:disabled) {
  color: #409eff;
  border-color: #409eff;
  background-color: #ecf5ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.pagination-container :deep(.btn-prev):disabled,
.pagination-container :deep(.btn-next):disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-container :deep(.el-pager) {
  display: flex;
  gap: 6px;
}

.pagination-container :deep(.el-pager li) {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  font-weight: 500;
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  transition: all 0.3s ease;
}

.pagination-container :deep(.el-pager li:not(.is-disabled):hover) {
  color: #409eff;
  border-color: #409eff;
  background-color: #ecf5ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.pagination-container :deep(.el-pager li.is-active) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-color: #409eff;
  color: #fff;
  font-weight: 600;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.pagination-container :deep(.el-pager li.is-disabled) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-container :deep(.el-pagination__jump) {
  margin-left: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.pagination-container :deep(.el-pagination__editor) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.pagination-container :deep(.el-pagination__editor):hover {
  border-color: #409eff;
}

.pagination-container :deep(.el-pagination__editor.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.pagination-container :deep(.el-input__inner) {
  text-align: center;
  font-weight: 500;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
  position: sticky;
  bottom: 0;
  background-color: #f5f5f5;
  z-index: 10;
}

.drawer-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

.drawer-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 仓库主管选择对话框样式 */
.supervisor-dialog {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.supervisor-dialog .search-input {
  width: 100%;
}

.search-icon {
  cursor: pointer;
  color: #a8abb2;
}

.supervisor-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
}

.list-title {
  padding: 12px 16px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.supervisor-item {
  padding: 12px 16px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.supervisor-item:last-child {
  border-bottom: none;
}

.supervisor-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.supervisor-item.is-selected {
  background-color: #d1f2eb;
  color: #303133;
  font-weight: 500;
}

.check-icon {
  font-size: 18px;
  font-weight: bold;
}

.empty-text {
  padding: 40px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.more-icon {
  cursor: pointer;
  color: #909399;
  font-size: 16px;
  transition: color 0.3s ease;
}

.more-icon:hover {
  color: #409eff;
}

/* 库管部门级联选择器样式 - 现代简约风格 */
.department-cascader-dialog {
  font-family: 'Microsoft YaHei', 'Source Han Sans CN', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.department-cascader-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.department-cascader-dialog :deep(.el-dialog__header) {
  padding: 24px 28px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
}

.department-cascader-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 700;
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
}

.department-cascader-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #ffffff;
  font-size: 20px;
  font-weight: bold;
}

.department-cascader-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #f0f0f0;
}

.department-cascader-dialog :deep(.el-dialog__body) {
  padding: 28px;
  background: linear-gradient(to bottom, #fafafa, #ffffff);
}

.department-cascader-dialog :deep(.el-dialog__footer) {
  padding: 20px 28px;
  background-color: #f8f9fa;
  border-top: 1px solid #e8e8e8;
}

.department-dialog {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.department-dialog .search-input {
  width: 100%;
}

.department-dialog .search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d9d9d9 inset;
  transition: all 0.3s ease;
  background: linear-gradient(to right, #ffffff, #f8f9fa);
  padding: 4px 12px;
}

.department-dialog .search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #1890ff inset, 0 2px 8px rgba(24, 144, 255, 0.15);
  background: #ffffff;
}

.department-dialog .search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.3) inset, 0 0 0 1px #1890ff inset;
  background: #ffffff;
}

.department-dialog .search-input :deep(.el-input__inner) {
  font-size: 15px;
  font-weight: 500;
}

.search-icon {
  color: #1890ff;
  font-size: 18px;
  transition: all 0.3s ease;
}

.department-dialog .search-input:hover .search-icon {
  color: #0050b3;
  transform: scale(1.1);
}

.department-tree-list {
  max-height: 480px;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background: linear-gradient(to bottom, #fafafa, #ffffff);
  padding: 12px 8px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

.department-tree-list::-webkit-scrollbar {
  width: 10px;
}

.department-tree-list::-webkit-scrollbar-track {
  background: #f0f0f0;
  border-radius: 5px;
  margin: 4px 0;
}

.department-tree-list::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #c0c0c0, #a0a0a0);
  border-radius: 5px;
  border: 2px solid #f0f0f0;
  transition: all 0.3s;
}

.department-tree-list::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #a0a0a0, #808080);
}

.tree-item {
  position: relative;
  margin: 2px 0;
}

/* 树形连接线 */
.tree-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 1px;
  background: linear-gradient(to bottom, #e0e0e0 0%, #e0e0e0 50%, transparent 50%);
  background-size: 1px 40px;
}

.tree-item:last-child::before {
  background: linear-gradient(to bottom, #e0e0e0 0%, #e0e0e0 20px, transparent 20px);
}

.tree-item-content {
  padding: 12px 16px;
  font-size: 14px;
  color: #262626;
  cursor: pointer;
  transition: all 0.25s ease;
  display: flex;
  align-items: center;
  position: relative;
  user-select: none;
  border-radius: 6px;
  margin: 0 4px;
  background-color: #ffffff;
  border: 1px solid transparent;
}

.tree-item-content::before {
  content: '';
  position: absolute;
  left: -20px;
  top: 50%;
  width: 20px;
  height: 1px;
  background: #e0e0e0;
}

.tree-item-content:hover {
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f4ff 100%);
  border-color: #b3d8ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.15);
  transform: translateX(2px);
}

.tree-item-content.is-selected {
  background: linear-gradient(135deg, #d4f1dd 0%, #c8edd5 100%);
  color: #262626;
  font-weight: 600;
  border-color: #95de64;
  box-shadow: 0 3px 12px rgba(82, 196, 58, 0.2);
  position: relative;
}

.tree-item-content.is-selected::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(to bottom, #52c41a, #73d13d);
  border-radius: 0 2px 2px 0;
}

.tree-item-expand {
  width: 24px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
  background-color: rgba(0, 0, 0, 0.02);
}

.tree-item-expand:hover {
  background-color: #e6f7ff;
  transform: scale(1.1);
}

.expand-arrow {
  color: #1890ff;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s ease;
  display: inline-block;
  transform-origin: center;
}

.tree-item-content:hover .expand-arrow {
  color: #0050b3;
  text-shadow: 0 0 4px rgba(24, 144, 255, 0.3);
}

.tree-item-label {
  flex: 1;
  font-size: 14px;
  line-height: 24px;
  font-weight: 500;
  letter-spacing: 0.3px;
}

/* 叶子节点标记 */
.leaf-dot {
  color: #52c41a;
  font-size: 18px;
  line-height: 1;
  text-shadow: 0 0 4px rgba(82, 196, 58, 0.3);
}

.tree-item-content:hover .leaf-dot {
  color: #73d13d;
  transform: scale(1.2);
}

.check-icon {
  color: #52c41a;
  font-size: 20px;
  font-weight: bold;
  margin-left: 12px;
  flex-shrink: 0;
  text-shadow: 0 0 8px rgba(82, 196, 58, 0.4);
  animation: checkPulse 1.5s ease-in-out infinite;
}

@keyframes checkPulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

.empty-text {
  padding: 40px 20px;
  text-align: center;
  color: #8c8c8c;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.dialog-footer .el-button {
  min-width: 100px;
  padding: 10px 24px;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0.5px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dialog-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.dialog-footer .el-button--primary:hover {
  background: linear-gradient(135deg, #5568d3 0%, #6a3f8f 100%);
}
</style>
